/**
 * 体重api
 * @author hejiacheng
 * @date 2021-12-3
 */

import {
  getTableOperate,
  getTableAggregate,
  getTableCommand
} from '../utils/cloudDatabaseUtil';
import { getDay, getHour, getMinute, getMonth, getSecond, getYear } from '../utils/dateUtil';
import { formatTime } from '../utils/formatUtil';

const tableName = 'weight'

/**
 * 添加体重
 * @param {时间对象} date 
 */
export function addWeight(data) {
  return new Promise(function (resolve, reject) {
    getTableOperate(tableName).add({
      data: data,
      success: function (res) {
        resolve && resolve(res)
      },
      fail: function (res) {
        reject && reject(res)
      }
    })
  })
}

/**
 * 删除体重
 * @param {时间对象} date 
 */
export function deleteWeight(data) {
  return new Promise(function (resolve, reject) {
    getTableOperate(tableName).doc(data).remove({
      success: function (res) {
        resolve && resolve(res)
      },
      fail: function (res) {
        reject && reject(res)
      }
    })
  })
}

/**
 * 查询体重
 * @param {时间对象} date 
 */
export function findWeightPage(data) {
  return new Promise(function (resolve, reject) {
    getTableOperate(tableName).where({
      })
      .skip(data.skip)
      .limit(data.pageSize) // 限制返回数量为 10 条
      .orderBy('dateTime', 'desc')
      .get({
        success: function (res) {
          resolve && resolve(res)
        },
        fail: function (event) {
          reject && reject(event)
        }
      })
  })
}

/**
 * 查询体重
 * @param {时间对象} date 
 */
export function findWeightList(data) {
  const $ = getTableAggregate()
  const _ = getTableCommand()
  let parmDateFmt = data.date.getTime()
  console.log("parmDateFmt : ", getYear(data.date) , "-", getMonth(data.date) , "-", getDay(data.date))
  console.log("parmDateFmt : ", parmDateFmt)
  return new Promise(function (resolve, reject) {
    getTableOperate(tableName).aggregate()
      .match({
        dateTimeStamp: _.gte(parmDateFmt)
      })
      .group({
        _id: '$' + data.groupField,
        weight: $.first('$weight'),
        date: $.first('$date'),
        dateTime: $.first('$dateTime'),
        time: $.first('$time'),
        openid: $.first('$_openid')
      })
      .sort({
        dateTime: 1,
      })
      .skip(0)
      .limit(100) // 限制返回数量为 10 条
      .end({
        success: function (res) {
          console.log("分组成功: ", res)
          resolve && resolve(res)
        },
        fail: function (event) {
          reject && reject(event)
        }
      })
  })
}